$(function () {
    let idKey = 'id'
    //实例化本地存储对象
    let localData = new LocalData('myDoList', idKey)
    let $todo = $('#todolist')
    let $done = $('#donelist')
    let $title = $('#title')
    loading()
    //新增数据对象构造工厂
    class DataObj {
        constructor(id = 1, title, done = false) {
            this.id = id
            this.title = title
            this.done = done
        }
    }
    //文本框回车事件
    $title.on('keyup', function (e) {
        let $val = $(this).val().trim()
        if (e.keyCode == 13) {
            if ($val.length == 0) return alert('请输入内容！')
            //实例化数据对象
            let dataObj = new DataObj(1, $val)
            //为实例化数据对象追加id值
            let newId = localData.addId(dataObj)
            dataObj.id = newId
            appendEle(dataObj)
            $(this).val('')
        }
    })
    //页面添加元素函数
    function appendEle(data) {
        //调用计数器
        let counterArr = localData.counter()
        $('#todocount').html(counterArr[0])
        $('#donecount').html(counterArr[1])    
        if (data.done) {
            $done.append(`<li><input type="checkbox" checked id = '${data.id}'><p>${data.title}</p> <a href="javascript:;" id = '${data.id}'></a></li>`)
        }
        else {
            $todo.append(`<li><input type="checkbox" id = '${data.id}'><p>${data.title}</p> <a href="javascript:;" id = '${data.id}'></a></li>`)
        }
    }
    //本地存储数据刷新函数
    function loading() {
        $('#todolist,#donelist').html('')
        let arr = localData.getData()
        arr.forEach(ele => {
            appendEle(ele)
        });
    }
    //完成&未完成事件函数
    $('#todolist,#donelist').on('change', 'li>input', function () {
        let id = $(this).attr('id')
        let done = $(this).prop('checked')
        localData.change(id, done)
        loading()
    })
    //删除事件
    $('#todolist,#donelist').on('click', 'a', function () {
        let id = $(this).attr('id')
        localData.delObj(id)
        loading()
    })
})